import 'dart:convert';
import 'dart:io';

import 'package:flui/flui.dart';
import 'package:flutter/cupertino.dart';
import 'package:jhtoast/jhtoast.dart';
import 'package:lepig/model/ResponseModel.dart';
import 'package:lepig/request/lib/NWApi.dart';
import 'package:lepig/request/lib/NWMethod.dart';

class HttpManager {
  static final HttpManager _shared = HttpManager._internal();

  factory HttpManager() => _shared;
  HttpClient httpClient;

  HttpManager._internal() {
    if (httpClient == null) {
      httpClient = new HttpClient();
    }
  }

  Future<dynamic> request(
      String path, NWMethod method, {Map<String, dynamic> params,BuildContext context}) async {
    print('------loadData_sys_get--------');
    Uri uri;
    HttpClientRequest request;
    if (method == NWMethod.GET) {
      var root=Uri.parse(NWApi.baseApi + path);
      uri = Uri( scheme:root.scheme, host: root.host,path: root.path, queryParameters: params);
      request = await httpClient.getUrl(uri);
    } else if (method == NWMethod.POST) {
      request = await httpClient.postUrl(Uri.parse(NWApi.baseApi + path));
    }

//    request.headers.add("X-Authorization", "");
    request.headers.add("Content-Type", "application/json;charset=UTF-8");
    if (method == NWMethod.POST) {
      request.add(utf8.encode(json.encode(params)));
    }
    var response = await request.close();
    var responseBody = await response.transform(Utf8Decoder()).join();
    if (response.statusCode == HttpStatus.ok) {
      Map data = jsonDecode(responseBody);
      ResponseModel responseModel = ResponseModel.fromJson(data);
      if (responseModel.success) {
//        return data["data"];
          return data;
      } else {
        JhToast.showError(context, msg:"请求失败:"+responseModel.code.toString()+"_"+ responseModel.message);
        print( "请求失败:"+responseModel.code.toString()+"_"+ responseModel.message);
      }
    } else {
      JhToast.showError(context,msg: "请求失败:" + response.statusCode.toString());
      return null;
    }
  }
}
